from http.server import HTTPServer, BaseHTTPRequestHandler
import json, subprocess
from logging import warning
from multiprocessing import Process
from traceback import print_stack
from urllib.parse import parse_qs
from pymysql import connect
from os import environ

db = connect(host='localhost',
  user='root',
  password=environ.get('password'),
  database='bsc_chain')

def get_params(path: str):
  i = path.index('?') + 1
  params_str = path[i:]
  return parse_qs(params_str)
 
class Resquest(BaseHTTPRequestHandler):
  def do_GET(self):
    self.send_response(200)
    self.send_header('Content-type', 'application/json')
    self.send_header('Access-Control-Allow-Origin', '*')
    self.end_headers()

    try:
      params = get_params(self.path)
      limit = 100
      offset = 0
      try:
        limit = int(params['limit'][0])
      except Exception as e:
        pass
      try:
        offset = int(params['offset'][0])
      except Exception as e:
        pass

      cursor = db.cursor()
      sql = f"select * from pancakepair order by id desc limit {offset},{limit}"
      cursor.execute(sql)
      sql_results = cursor.fetchall()
      res = {
        'pairs': [{'index': line[0], 'address': line[1]} for line in sql_results],
        'limit': limit,
        'offset': offset,
      }
      self.wfile.write(json.dumps(res).encode())
      self.close_connection()
    except Exception as e:
      print(e)
      print_stack()
  
    print('get end')
 
def start_serve_data():
  host = ('0.0.0.0', 8002)
  server = HTTPServer(host, Resquest)
  server.serve_forever()

if __name__ == '__main__':
  p = Process(target=start_serve_data)
  p.start()